<?php

namespace app\controller;

use plugin\admin\app\model\User;
use ReflectionClass;
use support\Request;
use Tinywan\Jwt\JwtToken;

/**
 * 基础控制器
 */
class ControllerBase
{
    protected Request $request;
    protected ?int $user_id = null; // 登录用户ID
    protected ?User $user = null; // 登录用户信息


    public function __construct()
    {
        $this->request = request();
        // 执行初始化逻辑
        $this->initialize();

    }

    /**
     * 初始化方法
     * 可用于子类扩展
     */
    protected function initialize()
    {
        try {
            $controller = new ReflectionClass($this->request->controller);
            $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];
        } catch (\ReflectionException $e) {
            $noNeedLogin = [];
        }


        // 需要登录验证的情况
        if (!in_array($this->request->action, $noNeedLogin)) {
            $this->user_id = JwtToken::getCurrentId();
            $userData = JwtToken::getUser();

            if ($userData) {
                // 如果返回的是数组或对象，则转为 User 模型实例
                $this->user = $userData instanceof User
                    ? $userData
                    : new User((array)$userData);
            }
        }
    }


}
